//
//  KLBookListCollectionViewController.m
//  KLBookCollection
//
//  Created by apple on 2017/10/17.
//  Copyright © 2017年 bonc. All rights reserved.
//

#import "KLBookListCollectionViewController.h"
#import "KLBookEntity.h"
#import "KLBookService.h"

#import "KLBookListCollectionViewCell.h"
#import "KLBookListCollectionViewCell+BookEntity.h"

#import "KLBookDetailController.h"

#import "MJRefresh.h"

static NSString *identifer = @"bookListCollectionViewCell";
static const CGFloat kCellGap = 10.0f;
static const CGFloat kBorderGap = 20.0f;
static const NSUInteger kColumnNumbers = 3;

@interface KLBookListCollectionViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray<KLBookEntity *> *bookEntites;
@property (nonatomic, assign, getter=isFirstLoad) BOOL firstLoad;//用于判断数据是否已经加载过一遍

@end

@implementation KLBookListCollectionViewController

#pragma mark - vc life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(FavorBookNotificationAction:) name:@"FavorBookNotification" object:nil];
    self.firstLoad = YES;
    [self initCollectionView];
    [self getDataWithOffset:0 pageSize:KLDefaultPageSize];
    
    __unsafe_unretained UICollectionView *collectionView = self.collectionView;
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    collectionView.mj_header.automaticallyChangeAlpha = YES;
    
    // 上拉加载更多
    collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self getDataWithOffset:self.bookEntites.count pageSize:KLDefaultPageSize];
    }];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if (!self.isFirstLoad) {
//                [self getDataWithOffset:0 pageSize:self.bookEntites.count];
//                [self.collectionView reloadData];
    }
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.firstLoad = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"FavorBookNotification" object:self];
}

#pragma mark - view init
- (void)initCollectionView {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    //collectionView
    CGFloat collectionViewWidth = self.view.frame.size.width - 2*kBorderGap;
    CGFloat collectionViewHeight = self.view.frame.size.height - 49;
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(kBorderGap, 0, collectionViewWidth, collectionViewHeight) collectionViewLayout:flowLayout];
    //cell
    CGFloat cellWidth = (collectionViewWidth-kCellGap*(kColumnNumbers-1))/kColumnNumbers;
    CGFloat cellHeight = cellWidth*1.5;
    
    flowLayout.itemSize = CGSizeMake(cellWidth, cellHeight);
    //横向间距
    flowLayout.minimumLineSpacing = kCellGap;
    //纵向间距
    flowLayout.minimumInteritemSpacing = kCellGap;
    //垂直滚动
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    //内边距上左下右
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    //register cell
    [collectionView registerClass:[KLBookListCollectionViewCell class] forCellWithReuseIdentifier:identifer];
    //register header
    [collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableView"];
    
    //delegate
    collectionView.delegate = self;
    collectionView.dataSource = self;
    
    //bg color
    collectionView.backgroundColor = [UIColor whiteColor];
    //自适应大小
    collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth |UIViewAutoresizingFlexibleHeight;
    
    
    self.collectionView = collectionView;
    [self.view addSubview:collectionView];
}

#pragma mark - data
- (void)getAllData {
    __weak typeof(self) weakSelf = self;
    [KLBookService getAllBookEntitiesWithCompletion:^(NSArray<KLBookEntity *> *bookEntites) {
        self.bookEntites = [bookEntites mutableCopy];
        [weakSelf.collectionView reloadData];
    }];
}

- (void)getDataWithOffset:(long long)offset pageSize:(NSUInteger)size {
    if (offset == 0) {
        [self.bookEntites removeAllObjects];
    }
    __weak typeof(self) weakSelf = self;
    [KLBookService getBookEntitiesWithOffset:offset pageSize:size completion:^(NSArray<KLBookEntity *> *bookEntites) {
        [self.bookEntites addObjectsFromArray:bookEntites];
        [weakSelf.collectionView.mj_footer endRefreshing];
        [weakSelf.collectionView reloadData];
    }];
}

#pragma mark - notification
- (void)FavorBookNotificationAction:(NSNotification *)notification{
    //    [self getDataWithOffset:0 pageSize:self.bookEntites.count];//这边还是原先的count，会出问题，所以重新刷新
    [self getDataWithOffset:0 pageSize:KLDefaultPageSize];
    NSLog(@"---接收到通知 collectionView---");
}

#pragma mark - Collection data source

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.bookEntites.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    KLBookListCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifer forIndexPath:indexPath];
    [cell sizeToFit];
    KLBookEntity *book = [self.bookEntites objectAtIndex:indexPath.row];
    [cell configureWithBookEntity:book];
    
    //如果在滚动中 不去设置图片 停止滚动后再开始设置图片
    if (!cell.coverImageView.image) {
        if (collectionView.dragging == NO && collectionView.decelerating == NO) {
            [cell startDownloadCoverImageWithBookEntity:book];
        }
    }
    
    return cell;
}

#pragma mark - Collection view delegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    KLBookEntity *book = [self.bookEntites objectAtIndex:indexPath.row];
    KLBookDetailController *detailVc = [[KLBookDetailController alloc] init];
    detailVc.bookEntity = book;
    [self.navigationController pushViewController:detailVc animated:YES];
}

#pragma mark - scroll view delegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (!decelerate) {
        [self loadCoverImageForVisibleCells];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self loadCoverImageForVisibleCells];
}

- (void)loadCoverImageForVisibleCells {
    NSArray<KLBookListCollectionViewCell *> *visibleCells = [self.collectionView visibleCells];
    for (KLBookListCollectionViewCell *cell in visibleCells) {
        NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
        KLBookEntity *book = [self.bookEntites objectAtIndex:indexPath.row];
        if (!cell.coverImageView.image) {
            [cell startDownloadCoverImageWithBookEntity:book];
        }
    }
}

#pragma mark - lazy load
- (NSMutableArray<KLBookEntity *> *)bookEntites {
    if (!_bookEntites) {
        _bookEntites = [@[] mutableCopy];
    }
    return _bookEntites;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
